<template>
  <div class="app-container">
    <el-row class="search">
      <el-select v-model="query.t" style="margin-right: 8px; width: 120px" placeholder="日期类型">
        <el-option v-for="item in [
          { label: '出院日期', value: '出院日期' },
          { label: '入院日期', value: '入院日期' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-date-picker v-model="query.stime" style="width: 150px" type="date" placeholder="开始" value-format="yyyy-MM-dd">
      </el-date-picker>
      <span>-</span>
      <el-date-picker v-model="query.etime" style="width: 150px" type="date" value-format="yyyy-MM-dd" placeholder="结束">
      </el-date-picker>

      <el-select v-model="query.ks" style="margin-right: 8px; width: 150px" placeholder="全院">
        <el-option v-for="item in deptLs" :key="item.value" :label="item.text" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="query.size" style="width: 80px; margin-right: 5px" placeholder="请选择">
        <el-option v-for="item in [10, 20, 50]" :key="item" :label="item" :value="item">
        </el-option>
      </el-select>

      <!-- <el-select
        v-model="query.order"
        style="width: 150px; margin-right: 5px"
        placeholder="请选择"
      >
        <el-option
          v-for="item in [
            '总人次',
            '并发症消耗过大',
            '费用超标',
            '治疗不足',
            '费用极低',
            '费用极高',
            '费用结构不合理',
            '违规项目较多',
            '人均盈亏',
            '人均可优化金额',
          ]"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>

      <el-select
        v-model="query.desc"
        style="width: 150px; margin-right: 5px"
        placeholder="请选择"
      >
        <el-option
          v-for="item in [
            {
              label: '降序',
              value: 'DESC',
            },
            {
              label: '升序',
              value: 'ASC',
            },
          ]"
          :key="item"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select> -->

      <el-button type="warning" @click="search" round>搜&nbsp;&nbsp;索</el-button>
    </el-row>

    <el-row>
      <el-table :data="ls" stripe style="width: 100%" v-loading="sLoading">
        <el-table-column prop="t" label="项目" width="200"> </el-table-column>
        <el-table-column v-for="item in cols" v-bind:key="item" :prop="item" :label="item">
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <div id="barChart" style="height: 400px; width: 100%" />
    </el-row>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { tplDetail, saveTpl, drgNames, drgInfo } from "@/api/PathTemplate";
import { drgwaring, dept2doc } from "@/api/patient";
import { GetTplById } from "@/api/pathway";
import { Format } from "@/utils/Utils";
import { autoName } from "@/api/commonApi";
import * as echarts from "echarts";
import { ECharts } from "echarts";
import { UserModule } from "@/store/modules/user";
@Component({
  name: "drgloss",
})
export default class extends Vue {
  public query = {
    t: "出院日期",
    stime: "" || this.$route.query.stime,
    etime: this.$route.query.etime || this.Format("yyyy-MM-dd", new Date()),
    grp: "编码",
    order: "盈亏",
    desc: "asc",
    size: 10,
    ks: '',
    rz: 1,
  };
  mounted() {
    // this.$nextTick(() => {
    //   this.initChart();
    // });
  }

  private deptLs: Array<any> = [];

  public async dept() {
    let curDate = new Date();
    let t = `${this.Format("yyyyMMddh", curDate)}${parseInt(
      curDate.getMinutes() / 5 + ""
    )}`;
    let d: any = await dept2doc({ t: t });

    d = d.data || [];

    let userdepts = await UserModule.GetUsername2depts();
    this.deptLs = [];
    if (userdepts.length > 0) {
      d = userdepts.map((it: any) => ({ 科室: it }));
      this.query.ks = userdepts[0]
    } else {
      this.deptLs.push({ text: "所有科室", value: "" })
    }

    this.deptLs.push(...d.map((it: any) => ({ text: it.科室, value: it.科室 })))

  }
  protected chart!: ECharts | null;
  private initChart(cols: Array<any>, vals: Array<any>) {
    let option = {
      title: {
        text: `亏损前${this.query.size}位的例均亏损（元）`,
        // subtext: "Example in MetricsGraphics.js",
        left: "center",
      },
      xAxis: {
        data: cols,
      },
      yAxis: {},
      series: [
        {
          type: "bar",
          data: vals,
          label: {
            show: true,
            position: "inside",
          },
        },
      ],
    };
    this.chart = echarts.init(
      document.getElementById("barChart") as HTMLDivElement
    );
    this.chart.setOption(option);
  }
  public fmt(row: any, column: any, cellValue: any) {
    let property = column.property;

    if (property == "入径率") {
      if (row.入组人次) {
        return (((row.是否入径 * 1.0) / row.入组人次) * 100).toFixed(2);
      }
    }
    if (row.总人次 > 0) {
      return parseInt((((row[property] * 1.0) / row.总人次) * 100).toString());
    }
    return 0;
  }
  private async created() {
    let cDate = new Date();
    let m = cDate.getMonth() - ((<any>window).MyConf["TIMEINTERVAL"] || "1");
    cDate.setMonth(m);
    if (!this.query.stime) {
      this.query.stime = this.Format("yyyy-MM-dd", cDate);
    }
    await this.dept();
    this.search();
  }

  public ls: Array<any> = [];
  public sLoading: boolean = false;
  public cols: Array<any> = [];

  public async search() {
    this.cols = [];
    this.sLoading = true;
    let q = JSON.parse(JSON.stringify(this.query));
    q.order += " " + q.desc;
    q.rj = "1"
    let d = await drgwaring(q);
    let data = d.data || [];
    this.cols = data.map((it: any) => it.编码);
    //console.log(JSON.stringify(this.cols));

    let tCols: any = [
      {
        t: "涉及人次",
        f: "入组人次",
      },
      {
        t: "并发症消耗过大人次",
        f: "并发症消耗过大",
      },
      {
        t: "费用超标人次",
        f: "费用超标",
      },
      {
        t: "治疗不足人次",
        f: "治疗不足",
      },
      {
        t: "费用极低人次",
        f: "费用极低",
      },
      {
        t: "费用极高人次",
        f: "费用极高",
      },
      {
        t: "费用结构不合理人次",
        f: "费用结构不合理",
      },
      {
        t: "违规项目较多人次",
        f: "违规项目较多",
      },
      {
        t: "总盈亏（元）",
        f: "盈亏",
      },
      {
        t: "人均盈亏（元）",
        f: "人均盈亏",
      },
      {
        t: "人均可优化金额（元）",
        f: "人均可优化金额",
      },
    ];

    let vals: Array<any> = [];

    for (let o of tCols) {
      for (let c of this.cols) {
        let ts = data.filter((it: any) => it.编码 == c);
        if (ts.length > 0) {
          o[c] = ts[0][o.f];
          if (o.f == "人均盈亏" || o.f == '人均可优化金额') {
            o[c] = (o[c] || 0).toFixed(2)
          }
          if (o.f == "盈亏") vals.push(parseFloat(o[c]));
          // if (o.f == "盈亏" || o.f == "可优化总金额") {
          //   let ts = data.filter((it: any) => it.编码 == c);
          //   let 入组人次 = 1;
          //   if (ts.length > 0) 入组人次 = ts[0].入组人次;
          //   o[c] = ((o[c] || 0) / 入组人次).toFixed(2);

          // }
        }
      }
    }
    this.initChart(this.cols, vals);
    this.ls = tCols;
    this.sLoading = false;
  }
  private Format(fmt: string, date: Date) {
    //author: meizz
    var o: any = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }

    return fmt;
  }
}
</script>